package com.qfjy.controller.homeWork917.liubingjian;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lbj
 * @Date 2021-09-17 10:51
 */
//目标类
public class MyTopic implements Subject{
    //观察者的集合
    private List<Observer> observers;
    //目标类会发布的信息
    private String message;
    //判断内容是否发生了改变，即状态是否发生改变
    private boolean changed;
    //定义一个类进行加锁
    private final Object MUTEX= new Object();
    public MyTopic(){
        this.observers=new ArrayList<>();
    }
    //将观察者加进集合
    @Override
    public void register(Observer obj) {
        if(obj == null) throw new NullPointerException("Null Observer");
        if(!observers.contains(obj)) {
            observers.add(obj);
        }
    }
    //将观察者移除集合
    @Override
    public void unregister(Observer obj) {
        observers.remove(obj);
    }
    //对观察者进行通知
    @Override
    public void notifyObservers() {
        List<Observer> observersLocal = null;
        synchronized (MUTEX) {
            if (!changed) {
                return;
            }
            observersLocal = new ArrayList<>(this.observers);
            this.changed=false;
        }
        for (Observer obj : observersLocal) {
            obj.update();
        }
    }
    //获得目标类的改变的信息
    @Override
    public Object getUpdate(Observer obj) {
        return this.message;
    }
    //向观察者发送状态改变的消息
    public void postMessage(String msg){
        System.out.println("Message Posted to Topic:"+msg);
        this.message=msg;
        this.changed=true;
        notifyObservers();
    }

}
